<template>
  <el-drawer
    v-model="drawerData.show"
    :size="drawerData.size"
    :title="title"
    :transfer="false"
    :close-on-click-modal="false"
    destroy-on-close
  >
    <BasicVxeForm ref="formRef" :formOptions="formOptions">
      <template #ciQuanZhongNumber="{ data, field }">
        <span
          style="
            display: block;
            width: 50px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid #c5c8ce;
            border-radius: 5px;
          "
          >{{ data[field] || 1 }}</span
        >
      </template>

      <template #ciQuanZhongAction="{ data }">
        <div style="display: flex; justify-content: flex-start; margin-top: 3px">
          <i
            class="iconfont-sys iconsys-tianjia"
            style="font-size: 25px; color: #2d8cf0; cursor: pointer"
            @click="handleCalcQuanZhong(data, 'plus')"
          ></i>
          <i
            class="iconfont-sys iconsys-shanchu"
            style="margin-left: 10px; font-size: 25px; color: #f34; cursor: pointer"
            @click="handleCalcQuanZhong(data, 'minus')"
          ></i>
        </div>
      </template>

      <template #ciQuanZhongNumber2="{ data, field }">
        <span
          style="
            display: block;
            width: 50px;
            height: 30px;
            line-height: 30px;
            text-align: center;
            border: 1px solid #c5c8ce;
            border-radius: 5px;
          "
          >{{ data[field] }}</span
        >
      </template>

      <template #state="{ data }">
        <div v-if="data.state === 1" style="width: 100%; height: 30px; background: #19be6b"></div>
        <div v-if="data.state === 0" style="width: 100%; height: 30px; background: red"></div>
      </template>
    </BasicVxeForm>

    <template #footer>
      <div style="flex: auto">
        <el-button @click="handleCancel">{{ $t('system.取消') }}</el-button>
        <el-button type="primary" :loading="submitting" @click="handleSubmit">{{
          $t('system.提交')
        }}</el-button>
      </div>
    </template>
  </el-drawer>
</template>

<script setup lang="ts">
  import { plus, minus } from '@/utils'
  import { postRenWuFeiPei } from '@/api/personAdmin'

  interface FormV0 {
    machineDocumentId: string
    tsId: string
    shiftName: string
    personDocumentId: string[]
    jobTitleRecordId: string
    ratio: string
    employeeDutySource: string
    remark: string
    ciQuanZhongNumber: string
    ciQuanZhongNumber2: string
  }

  interface OpenCallBackParams {
    type: 'add' | 'edit'
    detail?: Recordable
  }

  const props = defineProps<{
    renYuanOptions: LabelValueOption[]
  }>()

  const emits = defineEmits(['success'])

  const drawerData = reactive({
    show: false,
    size: 400
  })

  const reactData = ref<OpenCallBackParams>({} as OpenCallBackParams)
  const submitting = ref(false)

  const isUpdate = computed(() => reactData.value.type === 'edit')
  const title = computed(() => (!isUpdate.value ? '机台任务编辑' : '机台任务编辑'))

  const openDrawer = (show = true, data?: OpenCallBackParams) => {
    drawerData.show = show
    if (data) {
      // 等待渲染完成
      nextTick(() => {
        handleOpenCallback(data)
      })
    }
  }

  const closeDrawer = () => {
    drawerData.show = false
  }

  const handleCancel = () => {
    closeDrawer()
  }

  const handleOpenCallback = (data: OpenCallBackParams) => {
    // 每次打开重置表单
    formRef.value?.reset()

    reactData.value = data

    if (isUpdate.value) {
      formOptions.data = data.detail
    }
  }

  const handleCalcQuanZhong = (data, type: 'plus' | 'minus') => {
    const step = type === 'plus' ? 0.1 : -0.1

    if (
      (type === 'plus' && data.ciQuanZhongNumber < 0.9) ||
      (type === 'minus' && data.ciQuanZhongNumber > 0.1)
    ) {
      data.ciQuanZhongNumber = plus(data.ciQuanZhongNumber, step, 1)
      data.ciQuanZhongNumber2 = minus(data.ciQuanZhongNumber2, step, 1)
    }
  }

  const banCiZhuanHuan = (str) => {
    if (str == '01') {
      return '早'
    } else if (str == '02') {
      return '中'
    } else if (str == '03') {
      return '晚'
    }
  }

  const handleSubmit = async () => {
    try {
      const errMaps = await formRef.value?.validate()

      // 沒有错误才是校验成功
      if (!errMaps) {
        submitting.value = true
        const data = formRef.value!.getFormData()

        let str = data.tsId.toString().substr(6, 2)

        const submitData = data.personDocumentId.map((v, i) => ({
          machineDocumentId: data.machineDocumentId,
          tsId: data.tsId,
          shiftName: banCiZhuanHuan(str),
          personDocumentId: v,
          jobTitleRecordId: data.jobTitleRecordId,
          ratio: i === 0 ? data.ciQuanZhongNumber : data.ciQuanZhongNumber2,
          employeeDutySource: 0,
          remark: data.remark
        }))

        if (isUpdate.value) {
          await postRenWuFeiPei(submitData)
        }

        closeDrawer()
        emits('success')
      } else {
        ElMessage.error('请把必填项补全，检查无误后在提交')
      }
    } catch (err) {
      console.error(err)
    } finally {
      submitting.value = false
    }
  }

  const formRef = ref<BasicFormInstance<FormV0>>()
  const formOptions = reactive<BasicFormProps<FormV0>>({
    titleWidth: 80,
    data: {},
    rules: {
      personDocumentId: [{ required: true, content: '看台人不能为空' }]
    },
    items: [
      {
        field: 'gongXuName',
        title: '工序',
        span: 12
      },
      {
        field: 'scanTime',
        title: '时间',
        span: 12
      },
      {
        field: 'shiftName',
        title: '班次',
        span: 12
      },
      {
        field: 'machineNo',
        title: '机台号',
        span: 12
      },
      {
        field: 'title',
        title: '工种',
        span: 12
      },
      {
        field: 'employeeDutySourceStr',
        title: '来源',
        span: 12
      },
      {
        field: 'personDocumentId',
        title: '看台人',
        span: 24,
        itemRender: {
          name: 'ElSelect',
          options: computed(() => props.renYuanOptions) as unknown as LabelValueOption[],
          props: { multiple: true },
          events: {
            change: ({ data, field, item, $form }, e) => {
              const quanZhongItem = $form.getItemByField('ciQuanZhongNumber')
              const quanZhongItem2 = $form.getItemByField('ciQuanZhongNumber2')

              if (e && e.length > 2) {
                data[field] = e.slice(0, 2)
                ElMessage.warning('最多只能选择两个人')
              } else if (e && e.length === 2) {
                quanZhongItem &&
                  quanZhongItem2 &&
                  (quanZhongItem.titleWidth = quanZhongItem2.titleWidth = 110)

                if (!data.state) {
                  data.ciQuanZhongNumber = 0.5
                  data.ciQuanZhongNumber2 = 0.5
                }

                props.renYuanOptions.forEach((v) => {
                  if (v.value === e[0]) {
                    quanZhongItem && (quanZhongItem.title = `${v.label}-权重`)
                  } else if (v.value === e[1]) {
                    quanZhongItem2 && (quanZhongItem2.title = `${v.label}-权重`)
                  }
                })
              } else if (e.length < 2) {
                quanZhongItem && (quanZhongItem.title = `权重`)
                data.ciQuanZhongNumber = 1
                quanZhongItem &&
                  quanZhongItem2 &&
                  (quanZhongItem.titleWidth = quanZhongItem2.titleWidth = 80)
              }
            }
          }
        }
      },
      {
        field: 'ciQuanZhongNumber',
        title: '权重',
        span: 12,
        slots: {
          default: 'ciQuanZhongNumber'
        }
      },
      {
        field: 'ciQuanZhongAction',
        title: ' ',
        titleColon: false,
        span: 12,
        visibleMethod: ({ data }) => {
          return data.personDocumentId && data.personDocumentId.length === 2
        },
        slots: {
          default: 'ciQuanZhongAction'
        }
      },
      {
        field: 'ciQuanZhongNumber2',
        title: '权重',
        span: 12,
        visibleMethod: ({ data }) => {
          return data.personDocumentId && data.personDocumentId.length === 2
        },
        slots: {
          default: 'ciQuanZhongNumber2'
        }
      },
      {
        field: 'state',
        title: '状态',
        span: 12,
        slots: {
          default: 'state'
        }
      },
      {
        field: 'remark',
        title: '备注',
        span: 24,
        itemRender: {
          name: 'ElInput',
          props: { type: 'textarea', rows: 3, maxlength: 100, showWordLimit: true }
        }
      }
    ]
  })

  defineExpose({
    openDrawer,
    closeDrawer
  })
</script>
